<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Python 提供了两个级别访问的网络服务：  低级别的网络服务支持基本的 Socket，它提供了标准的 BSD Sockets API，可以访问底层操作系统Socket接口的全部方法。 高级别的网络服务模块 SocketServer， 它提供了服务器中心类，可以简化网络服务器的开发。####1. SocketSocket又称”套接字”，应用程序通常通过”套接字”向网络发出请求或者应答网络请求，使">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Python-学习(八)--网络操作">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Python/Python-学习(八)--网络操作/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="Python 提供了两个级别访问的网络服务：  低级别的网络服务支持基本的 Socket，它提供了标准的 BSD Sockets API，可以访问底层操作系统Socket接口的全部方法。 高级别的网络服务模块 SocketServer， 它提供了服务器中心类，可以简化网络服务器的开发。####1. SocketSocket又称”套接字”，应用程序通常通过”套接字”向网络发出请求或者应答网络请求，使">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-20fa8c0cafe0eb56.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-e3e003ab97ee2f70.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-1c3798006dc3db5c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:31:45.065Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python-学习(八)--网络操作">
<meta name="twitter:description" content="Python 提供了两个级别访问的网络服务：  低级别的网络服务支持基本的 Socket，它提供了标准的 BSD Sockets API，可以访问底层操作系统Socket接口的全部方法。 高级别的网络服务模块 SocketServer， 它提供了服务器中心类，可以简化网络服务器的开发。####1. SocketSocket又称”套接字”，应用程序通常通过”套接字”向网络发出请求或者应答网络请求，使">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-20fa8c0cafe0eb56.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Python/Python-学习(八)--网络操作/"/>





  <title>Python-学习(八)--网络操作 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Python/Python-学习(八)--网络操作/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python-学习(八)--网络操作</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Python 提供了两个级别访问的网络服务：</p>
<ul>
<li>低级别的网络服务支持基本的 Socket，它提供了标准的 BSD Sockets API，可以访问底层操作系统Socket接口的全部方法。</li>
<li>高级别的网络服务模块 SocketServer， 它提供了服务器中心类，可以简化网络服务器的开发。<br>####1. Socket<br>Socket又称”套接字”，应用程序通常通过”套接字”向网络发出请求或者应答网络请求，使主机间或者一台计算机上的进程间可以通讯。</li>
</ul>
<p><strong>socket()函数</strong><br>Python 中，我们用 socket（）函数来创建套接字，语法格式如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">socket.socket([family[, type[, proto]]])</span><br></pre></td></tr></table></figure></p>
<p>参数<br>family: 套接字家族可以使AF_UNIX或者AF_INET<br>type: 套接字类型可以根据是面向连接的还是非连接分为SOCK_STREAM或SOCK_DGRAM<br>protocol: 一般不填默认为0.<br><a id="more"></a></p>
<p>######Socket 对象(内建)方法</p>
<ul>
<li>服务器端套接字<br>1).  s.bind() :    绑定地址（host,port）到套接字， 在AF_INET下,以元组（host,port）的形式表示地址。<br>2). s.listen() : 开始TCP监听。backlog指定在拒绝连接之前，操作系统可以挂起的最大连接数量。该值至少为1，大部分应用程序设为5就可以了。<br>3). s.accept() : 被动接受TCP客户端连接,(阻塞式)等待连接的到来</li>
<li>客户端套接字<br>1). s.connect() : 主动初始化TCP服务器连接，。一般address的格式为元组（hostname,port），如果连接出错，返回socket.error错误。<br>2). s.connect_ex() : connect()函数的扩展版本,出错时返回出错码,而不是抛出异常</li>
<li>公共用途的套接字函数<br>1). s.recv() : 接收TCP数据，数据以字符串形式返回，bufsize指定要接收的最大数据量。flag提供有关消息的其他信息，通常可以忽略。<br>2). s.send() : 发送TCP数据，将string中的数据发送到连接的套接字。返回值是要发送的字节数量，该数量可能小于string的字节大小。<br>3). s.sendall() : 完整发送TCP数据，完整发送TCP数据。将string中的数据发送到连接的套接字，但在返回之前会尝试发送所有数据。成功返回None，失败则抛出异常。<br>4). s.recvfrom() : 接收UDP数据，与recv()类似，但返回值是（data,address）。其中data是包含接收数据的字符串，address是发送数据的套接字地址。<br>5). s.sendto() : 发送UDP数据，将数据发送到套接字，address是形式为（ipaddr，port）的元组，指定远程地址。返回值是发送的字节数。<br>6). s.close() : 关闭套接字<br>7). s.getpeername() : 返回连接套接字的远程地址。返回值通常是元组（ipaddr,port）。<br>8). s.getsockname() : 返回套接字自己的地址。通常是一个元组(ipaddr,port)<br>9). s.setsockopt(level,optname,value) : 设置给定套接字选项的值。<br>10). s.getsockopt(level,optname[.buflen]) : 返回套接字选项的值。<br>11). s.settimeout(timeout)     : 设置套接字操作的超时期，timeout是一个浮点数，单位是秒。值为None表示没有超时期。一般，超时期应该在刚创建套接字时设置，因为它们可能用于连接的操作（如connect()）<br>12). s.gettimeout() : 返回当前超时期的值，单位是秒，如果没有设置超时期，则返回None。<br>13). s.fileno() : 返回套接字的文件描述符。<br>14). s.setblocking(flag) : 如果flag为0，则将套接字设为非阻塞模式，否则将套接字设为阻塞模式（默认值）。非阻塞模式下，如果调用recv()没有发现任何数据，或send()调用无法立即发送数据，那么将引起socket.error异常。<br>15). s.makefile() : 创建一个与该套接字相关连的文件</li>
</ul>
<p>####2. Socket示例<br>1). 服务端<br>我们使用 socket 模块的 socket 函数来创建一个 socket 对象。socket 对象可以通过调用其他函数来设置一个 socket 服务。现在我们可以通过调用 bind(hostname, port) 函数来指定服务的 port(端口)。接着，我们调用 socket 对象的 accept 方法。该方法等待客户端的连接，并返回 connection 对象，表示已连接到客户端。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"># 文件名：server.py</span><br><span class="line"></span><br><span class="line"># 导入 socket、sys模块</span><br><span class="line">import socket</span><br><span class="line">import sys</span><br><span class="line"># 创建socket对象</span><br><span class="line">serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line"># 获取本地主机名</span><br><span class="line">host = socket.gethostname()</span><br><span class="line"># 设置端口</span><br><span class="line">port = 9999</span><br><span class="line"># 绑定端口号</span><br><span class="line">serversocket.bind((host, port))</span><br><span class="line"># 设置最大连接数, 超过后排队</span><br><span class="line">serversocket.listen(5)</span><br><span class="line"></span><br><span class="line">while True:</span><br><span class="line">	# 建立客户端连接</span><br><span class="line">	clientsocket, addr = serversocket.accept()</span><br><span class="line">	print(&quot;连接地址：%s&quot; % str(addr))</span><br><span class="line">	msg = &quot;欢迎访问小雨工作室&quot; + &quot;\r\n&quot;</span><br><span class="line">	clientsocket.send(msg.encode(&quot;utf-8&quot;))</span><br><span class="line">	clientsocket.close()</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure></p>
<p>2). 客户端<br>接下来我们写一个简单的客户端实例连接到以上创建的服务。端口号为 9999。<br>socket.connect(hosname, port ) 方法打开一个 TCP 连接到主机为 hostname 端口为 port 的服务商。连接后我们就可以从服务端后期数据，记住，操作完成后需要关闭连接。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"># 文件名：client.py</span><br><span class="line"></span><br><span class="line"># 导入 socket、sys模块</span><br><span class="line">import socket</span><br><span class="line">import sys</span><br><span class="line"></span><br><span class="line"># 创建socket对象</span><br><span class="line">s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line"># 获取本地主机名</span><br><span class="line">host = socket.gethostname()</span><br><span class="line"># 设置端口号</span><br><span class="line">port = 9999</span><br><span class="line"># 连接服务，指定主机和端口</span><br><span class="line">s.connect((host, port))</span><br><span class="line"># 接收小于1024字节的数据</span><br><span class="line">msg = s.recv(1024)</span><br><span class="line"># 关闭客户端</span><br><span class="line">s.close()</span><br><span class="line"></span><br><span class="line">print(msg.decode(&quot;utf-8&quot;))</span><br></pre></td></tr></table></figure></p>
<p>3). 运行结果：<br>打开两个命令提示符窗口，一个运行服务器，一个运行客户端。<br><img src="https://upload-images.jianshu.io/upload_images/3110861-20fa8c0cafe0eb56.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>####3. Python Internet 模块<br><img src="https://upload-images.jianshu.io/upload_images/3110861-e3e003ab97ee2f70.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####4. SMTP发送邮件<br>SMTP（Simple Mail Transfer Protocol）即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则，由它来控制信件的中转方式。python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。<br>1). Python创建 SMTP 对象语法如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">import smtplib</span><br><span class="line">smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )</span><br></pre></td></tr></table></figure></p>
<p>参数说明：</p>
<ul>
<li>host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:runoob.com，这个是可选参数。</li>
<li>port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号，一般情况下SMTP端口号为25。</li>
<li>local_hostname: 如果SMTP在你的本机上，你只需要指定服务器地址为 localhost 即可。</li>
</ul>
<p>2). Python SMTP对象使用sendmail方法发送邮件，语法如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]</span><br></pre></td></tr></table></figure></p>
<p>参数说明：</p>
<ul>
<li>from_addr: 邮件发送者地址。</li>
<li>to_addrs: 字符串列表，邮件发送地址。</li>
<li>msg: 发送消息(msg是字符串，表示邮件。我们知道邮件一般由标题，发信人，收件人，邮件内容，附件等构成，发送邮件的时候，要注意msg的格式。这个格式就是smtp协议中定义的格式)。</li>
</ul>
<p>3). 标准邮件需要三个头部信息： From, To, 和 Subject ，每个信息直接使用空行分割。<br>我们通过实例化 smtplib 模块的 SMTP 对象 smtpObj 来连接到 SMTP 访问，并使用 sendmail 方法来发送信息<br><strong>本机安装sendmail示例程序：</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"># 导入邮件模块</span><br><span class="line">import smtplib</span><br><span class="line">from email.mime.text import MIMEText</span><br><span class="line">from email.header import Header</span><br><span class="line"></span><br><span class="line"># 发送者邮箱</span><br><span class="line">sender= &quot;945541086@qq.com&quot;</span><br><span class="line"># 接收者邮箱</span><br><span class="line">receivers = [&quot;zaitingma@foxmail.com&quot;]</span><br><span class="line"></span><br><span class="line"># 三个参数：第一个是文本内容，第二个是文本格式，第三个是字符编码</span><br><span class="line">message = MIMEText(&quot;Python 邮件发送测试&quot;, &quot;plain&quot;, &quot;utf-8&quot;)</span><br><span class="line">message[&quot;From&quot;] = Header(&quot;小雨工作室&quot;, &quot;utf-8&quot;)</span><br><span class="line">message[&quot;To&quot;] = Header(&quot;测试&quot;, &quot;utf-8&quot;)</span><br><span class="line"></span><br><span class="line"># 设置主题</span><br><span class="line">subject = &quot;Python SMTP 邮件测试&quot;</span><br><span class="line">message[&quot;Subject&quot;] = Header(subject, &quot;utf-8&quot;)</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">	smtpObj = smtplib.SMTP(&quot;localhost&quot;)</span><br><span class="line">	smtpObj.sendmail(sender, receivers, message.as_toString())</span><br><span class="line">	print(&quot;邮件发送成功&quot;)</span><br><span class="line">	pass</span><br><span class="line">except Exception as e:</span><br><span class="line">	print(&quot;Error: 无法发送邮件&quot;)</span><br><span class="line">	raise e</span><br></pre></td></tr></table></figure></p>
<p><strong>本机未安装sendmail示例程序：</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">import smtplib</span><br><span class="line">from email.mime.text import MIMEText</span><br><span class="line">from email.header import Header</span><br><span class="line"></span><br><span class="line"># 第三方SMTP服务</span><br><span class="line"># 设置服务器</span><br><span class="line">mail_host=&quot;smtp.qq.com&quot;</span><br><span class="line"># 设置用户名</span><br><span class="line">mail_user=&quot;945541086@qq.com&quot;</span><br><span class="line"># 设置口令</span><br><span class="line">mail_pass=&quot;***********&quot;</span><br><span class="line"></span><br><span class="line"># 设置发送者</span><br><span class="line">sender = &quot;945541086@qq.com&quot;</span><br><span class="line"># 设置接收者</span><br><span class="line">receivers = [&quot;zaitingma@foxmail.com&quot;]</span><br><span class="line">message = MIMEText(&quot;Python 邮件发送测试&quot;,&quot;plain&quot;,&quot;utf-8&quot;)</span><br><span class="line">message[&quot;From&quot;] = Header(&quot;菜鸟教程&quot;,&quot;utf-8&quot;)</span><br><span class="line">message[&quot;To&quot;] = Header(&quot;测试&quot;, &quot;utf-8&quot;)</span><br><span class="line"># 设置主题</span><br><span class="line">subject = &quot;Python SMTP 邮件测试&quot;</span><br><span class="line">message[&quot;Subject&quot;] = Header(subject, &quot;utf-8&quot;)</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">	smtpObj = smtplib.SMTP()</span><br><span class="line">	# 25 为 SMTP 端口号</span><br><span class="line">	smtpObj.connect(mail_host, 25)</span><br><span class="line">	smtpObj.login(mail_user, mail_pass)</span><br><span class="line">	smtpObj.sendmail(sender, receivers, message.as_toString())</span><br><span class="line">	print(&quot;邮件发送成功&quot;)</span><br><span class="line">	pass</span><br><span class="line">except Exception as e:</span><br><span class="line">	print(&quot;Error: 无法发送邮件&quot;)</span><br><span class="line">	raise e</span><br></pre></td></tr></table></figure></p>
<p><strong>发送带网页的邮件:</strong><br>Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">import smtplib</span><br><span class="line">from email.mime.text import MIMEText</span><br><span class="line">from email.header import Header</span><br><span class="line"> </span><br><span class="line">sender = &apos;from@runoob.com&apos;</span><br><span class="line">receivers = [&apos;429240967@qq.com&apos;]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱</span><br><span class="line"> </span><br><span class="line">mail_msg = &quot;&quot;&quot;</span><br><span class="line">&lt;p&gt;Python 邮件发送测试...&lt;/p&gt;</span><br><span class="line">&lt;p&gt;&lt;a href=&quot;http://www.runoob.com&quot;&gt;这是一个链接&lt;/a&gt;&lt;/p&gt;</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">message = MIMEText(mail_msg, &apos;html&apos;, &apos;utf-8&apos;)</span><br><span class="line">message[&apos;From&apos;] = Header(&quot;菜鸟教程&quot;, &apos;utf-8&apos;)</span><br><span class="line">message[&apos;To&apos;] =  Header(&quot;测试&quot;, &apos;utf-8&apos;)</span><br><span class="line"> </span><br><span class="line">subject = &apos;Python SMTP 邮件测试&apos;</span><br><span class="line">message[&apos;Subject&apos;] = Header(subject, &apos;utf-8&apos;)</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">try:</span><br><span class="line">    smtpObj = smtplib.SMTP(&apos;localhost&apos;)</span><br><span class="line">    smtpObj.sendmail(sender, receivers, message.as_string())</span><br><span class="line">    print (&quot;邮件发送成功&quot;)</span><br><span class="line">except smtplib.SMTPException:</span><br><span class="line">    print (&quot;Error: 无法发送邮件&quot;)</span><br></pre></td></tr></table></figure></p>
<p><strong>发送带附件的邮件：</strong><br>发送带附件的邮件，首先要创建MIMEMultipart()实例，然后构造附件，如果有多个附件，可依次构造，最后利用smtplib.smtp发送。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">import smtplib</span><br><span class="line">from email.mime.text import MIMEText</span><br><span class="line">from email.mime.multipart import MIMEMultipart</span><br><span class="line">from email.header import Header</span><br><span class="line"> </span><br><span class="line">sender = &apos;from@runoob.com&apos;</span><br><span class="line">receivers = [&apos;429240967@qq.com&apos;]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱</span><br><span class="line"> </span><br><span class="line">#创建一个带附件的实例</span><br><span class="line">message = MIMEMultipart()</span><br><span class="line">message[&apos;From&apos;] = Header(&quot;菜鸟教程&quot;, &apos;utf-8&apos;)</span><br><span class="line">message[&apos;To&apos;] =  Header(&quot;测试&quot;, &apos;utf-8&apos;)</span><br><span class="line">subject = &apos;Python SMTP 邮件测试&apos;</span><br><span class="line">message[&apos;Subject&apos;] = Header(subject, &apos;utf-8&apos;)</span><br><span class="line"> </span><br><span class="line">#邮件正文内容</span><br><span class="line">message.attach(MIMEText(&apos;这是菜鸟教程Python 邮件发送测试……&apos;, &apos;plain&apos;, &apos;utf-8&apos;))</span><br><span class="line"> </span><br><span class="line"># 构造附件1，传送当前目录下的 test.txt 文件</span><br><span class="line">att1 = MIMEText(open(&apos;test.txt&apos;, &apos;rb&apos;).read(), &apos;base64&apos;, &apos;utf-8&apos;)</span><br><span class="line">att1[&quot;Content-Type&quot;] = &apos;application/octet-stream&apos;</span><br><span class="line"># 这里的filename可以任意写，写什么名字，邮件中显示什么名字</span><br><span class="line">att1[&quot;Content-Disposition&quot;] = &apos;attachment; filename=&quot;test.txt&quot;&apos;</span><br><span class="line">message.attach(att1)</span><br><span class="line"> </span><br><span class="line"># 构造附件2，传送当前目录下的 runoob.txt 文件</span><br><span class="line">att2 = MIMEText(open(&apos;runoob.txt&apos;, &apos;rb&apos;).read(), &apos;base64&apos;, &apos;utf-8&apos;)</span><br><span class="line">att2[&quot;Content-Type&quot;] = &apos;application/octet-stream&apos;</span><br><span class="line">att2[&quot;Content-Disposition&quot;] = &apos;attachment; filename=&quot;runoob.txt&quot;&apos;</span><br><span class="line">message.attach(att2)</span><br><span class="line"> </span><br><span class="line">try:</span><br><span class="line">    smtpObj = smtplib.SMTP(&apos;localhost&apos;)</span><br><span class="line">    smtpObj.sendmail(sender, receivers, message.as_string())</span><br><span class="line">    print (&quot;邮件发送成功&quot;)</span><br><span class="line">except smtplib.SMTPException:</span><br><span class="line">    print (&quot;Error: 无法发送邮件&quot;)</span><br></pre></td></tr></table></figure></p>
<p><strong>在 HTML 文本中添加图片:</strong><br>邮件的 HTML 文本中一般邮件服务商添加外链是无效的，正确添加突破的实例如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">import smtplib</span><br><span class="line">from email.mime.image import MIMEImage</span><br><span class="line">from email.mime.multipart import MIMEMultipart</span><br><span class="line">from email.mime.text import MIMEText</span><br><span class="line">from email.header import Header</span><br><span class="line"> </span><br><span class="line">sender = &apos;from@runoob.com&apos;</span><br><span class="line">receivers = [&apos;429240967@qq.com&apos;]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱</span><br><span class="line"> </span><br><span class="line">msgRoot = MIMEMultipart(&apos;related&apos;)</span><br><span class="line">msgRoot[&apos;From&apos;] = Header(&quot;菜鸟教程&quot;, &apos;utf-8&apos;)</span><br><span class="line">msgRoot[&apos;To&apos;] =  Header(&quot;测试&quot;, &apos;utf-8&apos;)</span><br><span class="line">subject = &apos;Python SMTP 邮件测试&apos;</span><br><span class="line">msgRoot[&apos;Subject&apos;] = Header(subject, &apos;utf-8&apos;)</span><br><span class="line"> </span><br><span class="line">msgAlternative = MIMEMultipart(&apos;alternative&apos;)</span><br><span class="line">msgRoot.attach(msgAlternative)</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">mail_msg = &quot;&quot;&quot;</span><br><span class="line">&lt;p&gt;Python 邮件发送测试...&lt;/p&gt;</span><br><span class="line">&lt;p&gt;&lt;a href=&quot;http://www.runoob.com&quot;&gt;菜鸟教程链接&lt;/a&gt;&lt;/p&gt;</span><br><span class="line">&lt;p&gt;图片演示：&lt;/p&gt;</span><br><span class="line">&lt;p&gt;&lt;img src=&quot;cid:image1&quot;&gt;&lt;/p&gt;</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">msgAlternative.attach(MIMEText(mail_msg, &apos;html&apos;, &apos;utf-8&apos;))</span><br><span class="line"> </span><br><span class="line"># 指定图片为当前目录</span><br><span class="line">fp = open(&apos;test.png&apos;, &apos;rb&apos;)</span><br><span class="line">msgImage = MIMEImage(fp.read())</span><br><span class="line">fp.close()</span><br><span class="line"> </span><br><span class="line"># 定义图片 ID，在 HTML 文本中引用</span><br><span class="line">msgImage.add_header(&apos;Content-ID&apos;, &apos;&lt;image1&gt;&apos;)</span><br><span class="line">msgRoot.attach(msgImage)</span><br><span class="line"> </span><br><span class="line">try:</span><br><span class="line">    smtpObj = smtplib.SMTP(&apos;localhost&apos;)</span><br><span class="line">    smtpObj.sendmail(sender, receivers, msgRoot.as_string())</span><br><span class="line">    print (&quot;邮件发送成功&quot;)</span><br><span class="line">except smtplib.SMTPException:</span><br><span class="line">    print (&quot;Error: 无法发送邮件&quot;)</span><br></pre></td></tr></table></figure></p>
<p><strong>QQ邮箱</strong><br>QQ 邮箱 SMTP 服务器地址：smtp.qq.com，ssl 端口：465<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">import smtplib</span><br><span class="line">from email.mime.text import MIMEText</span><br><span class="line">from email.utils import formataddr</span><br><span class="line"> </span><br><span class="line">my_sender=&apos;945541086@qq.com&apos;    # 发件人邮箱账号</span><br><span class="line">my_pass = &apos;**************&apos;              # 发件人邮箱授权码</span><br><span class="line">my_user=&apos;1425941077@qq.com&apos;      # 收件人邮箱账号，我这边发送给自己</span><br><span class="line">def mail():</span><br><span class="line">    ret=True</span><br><span class="line">    try:</span><br><span class="line">        msg=MIMEText(&apos;Python 测试邮件发送&apos;,&apos;plain&apos;,&apos;utf-8&apos;)</span><br><span class="line">        msg[&apos;From&apos;]=formataddr([&quot;Mazaiting&quot;,my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号</span><br><span class="line">        msg[&apos;To&apos;]=formataddr([&quot;FK&quot;,my_user])              # 括号里的对应收件人邮箱昵称、收件人邮箱账号</span><br><span class="line">        msg[&apos;Subject&apos;]=&quot;Python邮件测试&quot;                # 邮件的主题，也可以说是标题</span><br><span class="line"> </span><br><span class="line">        server=smtplib.SMTP_SSL(&quot;smtp.qq.com&quot;, 465)  # 发件人邮箱中的SMTP服务器，端口是25</span><br><span class="line">        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码</span><br><span class="line">        server.sendmail(my_sender,[my_user,],msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件</span><br><span class="line">        server.quit()  # 关闭连接</span><br><span class="line">    except Exception as e:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False</span><br><span class="line">        ret=False</span><br><span class="line">        raise e</span><br><span class="line">    return ret</span><br><span class="line"> </span><br><span class="line">ret=mail()</span><br><span class="line">if ret:</span><br><span class="line">    print(&quot;邮件发送成功&quot;)</span><br><span class="line">else :</span><br><span class="line">    print(&quot;邮件发送失败&quot;)</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-1c3798006dc3db5c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(五)/" rel="next" title="Python-学习(五)">
                <i class="fa fa-chevron-left"></i> Python-学习(五)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(六)/" rel="prev" title="Python-学习(六)">
                Python-学习(六) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
